package com.example.myys.ui.page.ysPage

import android.annotation.SuppressLint
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.ScrollableTabRow
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import com.example.myys.common.TopItem
import com.example.myys.data.entity.DataBean
import com.example.myys.ui.StateHandler
import com.example.myys.ui.base.DialogWithImage
import com.example.myys.ui.base.ListItem
import com.example.myys.ui.base.SearchBar
import com.example.myys.ui.page.syPage.YsPhbLb
import com.example.myys.viewModel.syModel.SyViewModel
import com.example.myys.viewModel.ysModel.YsViewModel
import com.google.gson.Gson

//导航栏数据类定义
object PagesYs {
    const val HOME = "Home" //影视首页
    const val MOVIE = "Movie" //电影
    const val TELEPLAY = "Teleplay" //电视剧
    const val ANIME = "Anime" //动漫
    const val VARIETY = "Variety" //综艺
    const val SHORTPLAY = "ShortPlay" //短剧
    const val LLP = "Llp"
    const val SS = "Ss" //搜索

    const val VIDEOPLAY = "VideoPlay" //视频播放页面
}

//影视展示
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Ys(navController: NavHostController, modifier: Modifier) {
    val viewModel: YsViewModel = viewModel()
    //导航
    val dataBar = listOf(
        TopItem(PagesYs.HOME, "首页"),
        TopItem(PagesYs.MOVIE, "电影"),
        TopItem(PagesYs.TELEPLAY, "电视剧"),
        TopItem(PagesYs.ANIME, "动漫"),
        TopItem(PagesYs.VARIETY, "综艺"),
        TopItem(PagesYs.SHORTPLAY, "短剧"),
        TopItem(PagesYs.LLP, "llp"),
        TopItem(PagesYs.SS, "搜索"),
    )
    var state by remember { viewModel.state }
    val scope = rememberCoroutineScope()


    Column(modifier) {
        ScrollableTabRow(selectedTabIndex = state) {
            dataBar.forEachIndexed { index, item ->
                Tab(text = {
                    Text(text = item.label)
                }, selected = state == index, onClick = {
                    state = index
                    viewModel.state.value = index;
                })
            }
        }

        when (state) {
            0 -> YsHome(navController, viewModel, searchClick = {
                viewModel.searchMovie(it.name)
                state = 7
            })

            1 -> YsMovieDy(navController, viewModel)
            2 -> YsMovieDsj(navController, viewModel)
            3 -> YsMovieDm(navController, viewModel)
            4 -> YsMovieZy(navController, viewModel)
            5 -> YsMovieDj(navController, viewModel)
            6 -> YsMovieLlp(navController, viewModel)
            7 -> YsMovieSearch(navController, viewModel)
        }

    }

}

@SuppressLint("SuspiciousIndentation")
@Composable
fun YsHome(
    navController: NavHostController,
    ysViewModel: YsViewModel,
    searchClick: (dataBean: DataBean) -> Unit
) {
    val syViewModel = SyViewModel()
    val ysState by syViewModel.ysState.collectAsState()
    val dsjState by syViewModel.dsjState.collectAsState()
    val zyState by syViewModel.zyState.collectAsState()
    val dmState by syViewModel.dmState.collectAsState()
    val djState by syViewModel.djState.collectAsState()
    val animeVideoState by ysViewModel.videoState.collectAsState()
    val sjState by ysViewModel.sjState.collectAsState()
    val view = LocalView.current

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState()),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        StateHandler(
            state = animeVideoState
        ) { resource ->
            resource.data?.let { movieList ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(5.dp)
                        .height(270.dp),
                ) {
                    Text(text = "推荐", modifier = Modifier.padding(10.dp))
                    LazyRow(
                        modifier = Modifier.padding(10.dp, 0.dp),
                        horizontalArrangement = Arrangement.spacedBy(5.dp)
                    ) {
                        itemsIndexed(movieList) { index, item ->
                            ItemYs(
                                item,
                                navController,
                                saveMovieSelf = { ysViewModel.addMovieShelf(item) })
                        }
                    }
                }
            }
        }
        StateHandler(
            state = sjState
        ) { resource ->
            resource.data?.let { movieList ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(5.dp)
                        .height(270.dp),
                ) {
                    Text(text = "收藏", modifier = Modifier.padding(10.dp))
                    LazyRow(
                        modifier = Modifier.padding(10.dp, 0.dp),
                        horizontalArrangement = Arrangement.spacedBy(5.dp)
                    ) {
                        itemsIndexed(movieList) { index, item ->
                            ListItem(dataBean = item, onClickItem = {
                                navController.navigate(
                                    "${PagesYs.VIDEOPLAY}?data=" + Gson().toJson(it)
                                )
                            }, onDeleteClick = {
                                ysViewModel.deleteMovieShelf(it)
                            }, isDeleteAble = true)
                        }
                    }
                }
            }
        }

        Card(
            modifier = Modifier
                .padding(5.dp)
                .fillMaxWidth()
                .height(500.dp)
        ) {
            Text(text = "排行榜", modifier = Modifier.padding(10.dp))
            LazyRow(modifier = Modifier.padding(10.dp, 0.dp)) {
                item(key = "电影") { YsPhbLb(name = "电影", ysState, onClickItem = searchClick) }
                item(key = "电视剧") {
                    YsPhbLb(
                        name = "电视剧",
                        dsjState,
                        onClickItem = searchClick
                    )
                }
                item(key = "动漫") { YsPhbLb(name = "动漫", dmState, onClickItem = searchClick) }
                item(key = "综艺") { YsPhbLb(name = "综艺", zyState, onClickItem = searchClick) }
                item(key = "短剧") { YsPhbLb(name = "短剧", djState, onClickItem = searchClick) }
            }
        }
    }
}

@Composable
fun YsMovieDy(navController: NavHostController, ysViewModel: YsViewModel) {
    LaunchedEffect(Unit) {
        ysViewModel.getDyDataListByType()
    }
    val dyState by ysViewModel.dyState.collectAsState()
    StateHandler(
        state = dyState
    ) { resource ->
        resource.data?.let { movieList ->
            Column {
                LazyVerticalGrid(
                    columns = GridCells.Adaptive(minSize = 300.dp),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    itemsIndexed(movieList) { index, item ->
                        ItemYs(
                            item,
                            navController,
                            saveMovieSelf = { ysViewModel.addMovieShelf(item) })
                        LaunchedEffect(movieList.size) {
                            if (movieList.size - index < 2) {
                                ysViewModel.getDyDataListByType(1)
                            }
                        }
                    }
                }
            }
        }
    }
}

@SuppressLint("UnrememberedMutableState")
@Composable
fun YsMovieDsj(navController: NavHostController, ysViewModel: YsViewModel) {
    LaunchedEffect(Unit) {
        ysViewModel.getDsjDataListByType()
    }
    val dsjState by ysViewModel.dsjState.collectAsState()
    StateHandler(
        state = dsjState
    ) { resource ->
        resource.data?.let { movieList ->
            Column {
                LazyVerticalGrid(
                    columns = GridCells.Adaptive(minSize = 300.dp),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    itemsIndexed(movieList) { index, item ->
                        ItemYs(
                            item,
                            navController,
                            saveMovieSelf = { ysViewModel.addMovieShelf(item) })
                        LaunchedEffect(movieList.size) {
                            if (movieList.size - index < 2) {
                                ysViewModel.getDsjDataListByType(1)
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun YsMovieDm(navController: NavHostController, ysViewModel: YsViewModel) {
    LaunchedEffect(Unit) {
        ysViewModel.getDmDataListByType()
    }
    val dmState by ysViewModel.dmState.collectAsState()
    StateHandler(
        state = dmState
    ) { resource ->
        resource.data?.let { movieList ->
            Column {
                LazyVerticalGrid(
                    columns = GridCells.Adaptive(minSize = 300.dp),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    itemsIndexed(movieList) { index, item ->
                        ItemYs(
                            item,
                            navController,
                            saveMovieSelf = { ysViewModel.addMovieShelf(item) })
                        LaunchedEffect(movieList.size) {
                            if (movieList.size - index < 2) {
                                ysViewModel.getDmDataListByType(1)
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun YsMovieZy(navController: NavHostController, ysViewModel: YsViewModel) {
    LaunchedEffect(Unit) {
        ysViewModel.getZyDataListByType()
    }
    val zyState by ysViewModel.zyState.collectAsState()
    StateHandler(
        state = zyState
    ) { resource ->
        resource.data?.let { movieList ->
            Column {
                LazyVerticalGrid(
                    columns = GridCells.Adaptive(minSize = 300.dp),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    itemsIndexed(movieList) { index, item ->
                        ItemYs(
                            item,
                            navController,
                            saveMovieSelf = { ysViewModel.addMovieShelf(item) })
                        LaunchedEffect(movieList.size) {
                            if (movieList.size - index < 2) {
                                ysViewModel.getZyDataListByType(1)
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun YsMovieDj(navController: NavHostController, ysViewModel: YsViewModel) {
    LaunchedEffect(Unit) {
        ysViewModel.getDjDataListByType()
    }
    val djState by ysViewModel.djState.collectAsState()
    StateHandler(
        state = djState
    ) { resource ->
        resource.data?.let { movieList ->
            Column {
                LazyVerticalGrid(
                    columns = GridCells.Adaptive(minSize = 300.dp),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    itemsIndexed(movieList) { index, item ->
                        ItemYs(
                            item,
                            navController,
                            saveMovieSelf = { ysViewModel.addMovieShelf(item) })
                        LaunchedEffect(movieList.size) {
                            if (movieList.size - index < 2) {
                                ysViewModel.getDjDataListByType(1)
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun YsMovieLlp(navController: NavHostController, ysViewModel: YsViewModel) {
    LaunchedEffect(Unit) {
        ysViewModel.getLlpDataListByType()
    }
    val llpState by ysViewModel.llpState.collectAsState()
    StateHandler(
        state = llpState
    ) { resource ->
        resource.data?.let { movieList ->
            Column {
                LazyVerticalGrid(
                    columns = GridCells.Adaptive(minSize = 300.dp),
                    horizontalArrangement = Arrangement.spacedBy(10.dp),
                    verticalArrangement = Arrangement.spacedBy(10.dp)
                ) {
                    itemsIndexed(movieList) { index, item ->
                        ItemYs(
                            item,
                            navController,
                            saveMovieSelf = { ysViewModel.addMovieShelf(item) })
                        LaunchedEffect(movieList.size) {
                            if (movieList.size - index < 2) {
                                ysViewModel.getLlpDataListByType(1)
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun YsMovieSearch(navController: NavHostController, ysViewModel: YsViewModel) {
    val ssState by ysViewModel.ssState.collectAsState()
    Column {
        SearchBar(onSearchClick = {
            ysViewModel.searchMovie(it)
        })
        StateHandler(state = ssState) { resource ->
            resource.data?.let { movieList ->
                if (movieList.isEmpty()) {
                    Text(text = "无数据")
                }
                Column {
                    LazyVerticalGrid(
                        columns = GridCells.Adaptive(minSize = 300.dp),
                        horizontalArrangement = Arrangement.spacedBy(10.dp),
                        verticalArrangement = Arrangement.spacedBy(10.dp)
                    ) {
                        itemsIndexed(movieList) { index, item ->
                            ItemYs(
                                item,
                                navController,
                                saveMovieSelf = { ysViewModel.addMovieShelf(item) })
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun ItemYs(itemData: DataBean, navController: NavController, saveMovieSelf: () -> Unit) {
    // 获取 context
    val context = LocalContext.current
    //详情弹窗
    var dialogShow by remember {
        mutableStateOf(false)
    }
    ListItem(onClickItem = { dataBean ->
        Toast.makeText(context, "链接:" + dataBean.url, Toast.LENGTH_LONG)
            .show()
        dialogShow = true
    }, dataBean = itemData)
    if (dialogShow) {
        DialogWithImage(
            onDismissRequest = { dialogShow = false },
            onPlay = {
                navController.navigate("${PagesYs.VIDEOPLAY}?data=" + Gson().toJson(itemData))
            },
            onConfirmation = {
                saveMovieSelf()
                Toast.makeText(context, "加入收藏成功", Toast.LENGTH_SHORT).show()
                dialogShow = false
            },
            itemData
        )
    }
}